package com.ltmall.api.manager.impl;

import com.ltmall.api.bean.*;
import com.ltmall.api.dao.impl.AccountDAO;
import com.ltmall.api.dao.impl.OrderDAO;
import com.ltmall.api.dao.impl.SubUnderwritingDAO;
import com.ltmall.api.entity.*;
import com.ltmall.api.manager.AccountManager;
import com.ltmall.api.manager.SubUnderwritingManager;
import com.ltmall.api.util.PageUtil;
import com.ltmall.api.weixin.util.Constant;
import com.ltmall.api.weixin.util.QRCodeUtil;
import com.ltmall.api.weixin.util.TemplateMessageUtil;
import com.wuwangkeji.homeflavor.comm.Path;

import java.io.File;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class SubUnderwritingManagerImpl implements SubUnderwritingManager {

    private SubUnderwritingDAO suDAO;
    private AccountDAO         aDAO;
    private OrderDAO           oDAO;
    private AccountManager     accountManager;

    public SubUnderwritingDAO getSuDAO() {
        return suDAO;
    }

    public void setSuDAO(SubUnderwritingDAO suDAO) {
        this.suDAO = suDAO;
    }

    public AccountDAO getaDAO() {
        return aDAO;
    }

    public void setaDAO(AccountDAO aDAO) {
        this.aDAO = aDAO;
    }

    public OrderDAO getoDAO() {
        return oDAO;
    }

    public void setoDAO(OrderDAO oDAO) {
        this.oDAO = oDAO;
    }

    public AccountManager getAccountManager() {
        return accountManager;
    }

    public void setAccountManager(AccountManager accountManager) {
        this.accountManager = accountManager;
    }

    public ThSubUnderwriters subUnderwriterGet(int subUndId) {
        return suDAO.subUnderwriterGet(subUndId);
    }

    public ThJsonSubUnderwriterRegisterNecessary subUnderwriterRegisterNecessary(int userId) {
        ThJsonSubUnderwriterRegisterNecessary necessary = new ThJsonSubUnderwriterRegisterNecessary();

        ThSubUnderwriters subUnd = suDAO.subUnderwriterGet(userId);
        if (subUnd != null) {
            necessary.setState(2);
            return necessary;
        }

        int orderCount = oDAO.closedOrderCount(userId);

        if (orderCount == 0) {
            necessary.setState(0);
            return necessary;
        }

        necessary.setState(1);
        List<ThSubUnderwritingConfigs> configList = suDAO.subUnderwritingConfigList();
        if (configList != null) {
            for (ThSubUnderwritingConfigs config : configList) {
                if (config.getName() == "registerGuideImage") {
                    necessary.setGuideImage(Path.nginx_server_dir_platform + Path.SUBUNDERWRITING
                                            + File.separator + config.getValue());
                }
            }
        }
        return necessary;
    }

    public ThJsonSubUnderwriter subUnderwriterInfoGet(int subUndId) {
        ThSubUnderwriters subUnd = suDAO.subUnderwriterGet(subUndId);
        if (subUnd == null) {
            return null;
        }

        ClientInfo subUndInfo = aDAO.getInfo(subUndId);
        ThUserLevels level = aDAO.userLevelGet(subUndInfo.getLevelId());

        BigDecimal totalSalesAmount = suDAO.subUnderwritingOrderTotalSalesAmount(subUndId);
        BigDecimal totalEstimatedIncome = suDAO.getEstimatedProfitShare(subUndId);

        int fansCount = suDAO.subUnderwriterFansCount(subUndId);

        ThJsonSubUnderwriter jsonSubUnd = new ThJsonSubUnderwriter();
        jsonSubUnd.setId(subUnd.getId());
        jsonSubUnd.setLevelId(level.getId());
        jsonSubUnd.setLevelName(level.getTitle());
        jsonSubUnd.setFansCount(fansCount);
        jsonSubUnd.setReferrer(referrerInfo(subUndId));
        jsonSubUnd.setTotalSalesAmount(totalSalesAmount);
        jsonSubUnd.setTotalIncome(subUnd.getTotalIncome());
        jsonSubUnd.setTotalExtraction(subUnd.getTotalOutcome());
        jsonSubUnd.setTotalEstimatedIncome(totalEstimatedIncome);

        return jsonSubUnd;
    }

    public Object[] subUnderwriterInfo(int fansId) {
        return suDAO.subUnderwriterInfo(fansId);
    }

    public ThJsonSubUnderwriterQRCodeInfo subUnderwriterQRCodeInfoGet(int subUndId) {
        ThSubUnderwriterQrCodes qrCode = suDAO.subUnderwriterQRCodeGet(subUndId);

        if (qrCode == null
            || !org.apache.commons.lang.time.DateUtils.isSameDay(qrCode.getQrCodeCreatedAt(),
                new Date())) {
            String qrCodeUrl = QRCodeUtil.getShortTermQRCodeUrl(subUndId);
            ClientInfo info = aDAO.getInfo(subUndId);

            if (qrCodeUrl == null) {
                return null;
            }

            String qrCodeName = QRCodeUtil.compositeAvatar(qrCodeUrl, info.getPhoto());

            if (qrCodeName == null) {
                return null;
            }

            if (qrCode == null) {
                qrCode = new ThSubUnderwriterQrCodes();
                qrCode.setSubUnderwriterId(subUndId);
                qrCode.setCreatedAt(new Date());
            }

            qrCode.setQrCode(qrCodeName);
            qrCode.setQrCodeCreatedAt(new Date());
            qrCode.setSyntheticImage(null);
            qrCode.setUpdatedAt(new Date());
            suDAO.subUnderwriterQRCodeSaveOrUpdate(qrCode);
        }

        ThJsonSubUnderwriterQRCodeInfo info = new ThJsonSubUnderwriterQRCodeInfo();
        // 使用域名来保证同源不跨域
        info.setQrCode(Constant.getImageDomain() + File.separator + Path.project + File.separator
                       + "upload" + File.separator + Path.PLATFORM + File.separator
                       + Path.SUBUNDERWRITING + File.separator + qrCode.getQrCode());
        info.setInvalidTime(qrCode.getQrCodeCreatedAt().getTime() + 2592000 * 1000l);
        if (qrCode.getSyntheticImage() != null) {
            info.setSyntheticImage(Constant.getImageDomain() + File.separator + Path.project
                                   + File.separator + "upload" + File.separator + Path.PLATFORM
                                   + File.separator + Path.SUBUNDERWRITING + File.separator
                                   + qrCode.getSyntheticImage());
        }

        return info;
    }

    public boolean subUnderwriterQRCodeImageUpdate(int subUndId, String image) {
        return suDAO.subUnderwriterQRCodeImageUpdate(subUndId, image);
    }

    public boolean subUnderwriterAdd(int subUndId) {
        ThSubUnderwriters subUnd = new ThSubUnderwriters();
        subUnd.setId(subUndId);
        subUnd.setState(1);
        subUnd.setTotalSalesAmount(BigDecimal.valueOf(0));
        subUnd.setTotalIncome(BigDecimal.valueOf(0));
        subUnd.setTotalOutcome(BigDecimal.valueOf(0));

        return suDAO.subUnderwriterAdd(subUnd);
    }

    public boolean subUnderwriterUpdate(ThSubUnderwriters subUnd) {
        return suDAO.subUnderwriterUpdate(subUnd);
    }

    public boolean subUnderwriterTotalOutcomeUpdate(int subUndId, BigDecimal totalOutcome) {
        return suDAO.subUnderwriterTotalOutcomeUpdate(subUndId, totalOutcome);
    }

    public List<ThJsonSubUnderwriterFans> subUnderwriterFansList(int subUndId, PageUtil page) {
        List<?> list = suDAO.subUnderwriterFansList(subUndId, page);

        List<ThJsonSubUnderwriterFans> jsonList = new ArrayList<ThJsonSubUnderwriterFans>();
        for (int i = 0; i < list.size(); i++) {
            Object[] obj = (Object[]) list.get(i);
            ThJsonSubUnderwriterFans fans = new ThJsonSubUnderwriterFans();
            fans.setFansId(Integer.parseInt(obj[0].toString()));
            fans.setFansName(obj[1].toString());
            fans.setFansAvatar(obj[2].toString());
            fans.setLevelId(Integer.parseInt(obj[3].toString()));
            fans.setFollowTime(((Timestamp) obj[4]).getTime());

            jsonList.add(fans);
        }

        return jsonList;
    }

    public int subUnderwriterFansCount(int subUndId) {
        return suDAO.subUnderwriterFansCount(subUndId);
    }

    public boolean subUnderwriterFansAdd(ThSubUnderwriterFans fans) {
        return suDAO.subUnderwriterFansAdd(fans);
    }

    public List<ThJsonSubUnderwriterOrder> subUnderwritingOrderList(int subUndId, String fansName,
                                                                    PageUtil page) {
        List<?> list = suDAO.subUnderwritingOrderList(subUndId, fansName, page);

        List<ThJsonSubUnderwriterOrder> jsonList = new ArrayList<ThJsonSubUnderwriterOrder>();
        for (int i = 0; i < list.size(); i++) {
            Object[] obj = (Object[]) list.get(i);
            ThJsonSubUnderwriterOrder order = new ThJsonSubUnderwriterOrder();
            order.setOrderId((Integer) obj[0]);
            order.setTotalFee((BigDecimal) obj[2]);
            order.setSubUnderwritingFee(((BigDecimal) obj[2]).multiply((BigDecimal) obj[3]));
            order.setCreatedTime(((Timestamp) obj[4]).getTime());
            order.setFansId(Integer.parseInt(obj[5].toString()));
            order.setFansName((String) obj[6]);
            order.setFansAvatar((String) obj[7]);
            // 虚拟出了状态10，为订单完全关闭已发放佣金状态。
            order.setState(Integer.parseInt(obj[1].toString()) == 1 ? 10 : Integer.parseInt(obj[8]
                .toString()));
            order.setMaxProfitShare(new BigDecimal(obj[9].toString()).divide(new BigDecimal(100)));

            jsonList.add(order);
        }

        return jsonList;
    }

    public boolean subUnderwritingOrderExistence(int orderId) {
        return suDAO.subUnderwritingOrderExistence(orderId);
    }

    public boolean subUnderwritingOrderAdd(ThSubUnderwritingOrders order) {
        return suDAO.subUnderwritingOrderAdd(order);
    }

    public boolean wechatRedPackOutcomeAdd(ThRedPackOutcomes redPack) {
        return suDAO.wechatRedPackOutcomeAdd(redPack);
    }

    public boolean wechatRedPackOutcomeUpdate(ThRedPackOutcomes redPack) {
        return suDAO.wechatRedPackOutcomeUpdate(redPack);
    }

    public boolean subUnderwritingOutcomeAdd(ThSubUnderwritingOutcomes outcome) {
        return suDAO.subUnderwritingOutcomeAdd(outcome);
    }

    public boolean subUnderwritingOutcomeAdd(int userId, BigDecimal amount, int channelType,
                                             int channelId, int state) {
        ThSubUnderwritingOutcomes outcomeRecord = new ThSubUnderwritingOutcomes();
        outcomeRecord.setAmount(amount);
        outcomeRecord.setState(state);
        outcomeRecord.setUserId(userId);
        outcomeRecord.setChannelType(channelType);
        outcomeRecord.setChannelId(channelId);

        return suDAO.subUnderwritingOutcomeAdd(outcomeRecord);
    }

    public List<ThSubUnderwritingOutcomes> subUnderwritingOutcomeList(int subUndId, PageUtil page) {
        return suDAO.subUnderwritingOutcomeList(subUndId, page);
    }

    public List<ThSubUnderwritingIncomes> subUnderwritingIncomeList(int subUndId, int type,
                                                                    PageUtil page) {
        return subUnderwritingIncomeList(subUndId, type, page);
    }

    public List<ThJsonFansLevelUpIncome> subUnderwriterFansLevelUpIncomeList(int subUndId,
                                                                             PageUtil page) {
        List<?> list = suDAO.subUnderwriterFansLevelUpIncomeList(subUndId, page);

        List<ThJsonFansLevelUpIncome> jsonList = new ArrayList<ThJsonFansLevelUpIncome>();
        for (int i = 0; i < list.size(); i++) {
            Object[] obj = (Object[]) list.get(i);
            ThJsonFansLevelUpIncome income = new ThJsonFansLevelUpIncome();
            income.setId(Integer.parseInt(obj[0].toString()));
            income.setFansId(Integer.parseInt(obj[1].toString()));
            income.setLevelId(Integer.parseInt(obj[2].toString()));
            income.setIncome((BigDecimal) obj[3]);
            income.setDate(((Date) obj[4]).getTime());
            income.setFansName(obj[5].toString());
            income.setAvatar(obj[6].toString());
            income.setLevelName(obj[7].toString());

            jsonList.add(income);
        }

        return jsonList;
    }

    public int fansCountGetByLevelId(int level, int userID) {
        return suDAO.fansCountGetByLevelId(level, userID);
    }

    public List<ClientInfo> fansInfoGetByLevelId(int level, int userID, PageUtil page) {
        return suDAO.fansInfoGetByLevelId(level, userID, page);
    }

    public List<?> rewardGotFansInfoGetByUserId(int userID, PageUtil page) {
        return suDAO.rewardGotFansInfoGetByUserId(userID, page);
    }

    public int myFansCountGetByMonth(int level, int userID, Date startTime, Date endTime) {
        return suDAO.myFansCountGetByMonth(level, userID, startTime, endTime);
    }

    public List<?> myRewardHistoryFansInfoGetByMonth(int userID, PageUtil page) {
        return suDAO.myRewardHistoryFansInfoGetByMonth(userID, page);
    }

    public List<?> directorPrivilegeOrderIncomesInfoGetByMonth(String type ,int userID, PageUtil page) {
        return suDAO.directorPrivilegeOrderIncomesInfoGetByMonth(type,userID, page);
    }

    public Object[] referrerInfo(int userId) {
        return suDAO.referrerInfo(userId);
    }

    public ThSubUnderwriterQrCodes getLimitQRCodeInfo(int userId) {
        return suDAO.subUnderwriterLimitQrCodes(userId);
    }

    public boolean saveQRCode(ThSubUnderwriterQrCodes qrCode) {
        return suDAO.subUnderwriterQRCodeSaveOrUpdate(qrCode);
    }

    /**
     * @see com.ltmall.api.manager.SubUnderwritingManager#addSubUnderwriterFans(int, String)
     * @author x1ny
     */
    public void addSubUnderwriterFans(int userId, String subUnderwriterIdStr) {
        if (subUnderwriterIdStr == null || subUnderwriterIdStr.equals("")) {
            return;
        }

        int subUnderwriterId = Integer.parseInt(subUnderwriterIdStr);
        ThSubUnderwriters subUnderwriter = subUnderwriterGet(subUnderwriterId);
        if (subUnderwriter == null) {
            return;
        }
        ThSubUnderwriterFans fans = new ThSubUnderwriterFans();
        fans.setSubUnderwriterId(subUnderwriterId);
        fans.setFansId(userId);
        subUnderwriterFansAdd(fans);

        // 判断是否申请成功未满一个月
        long interval = 30 * 24 * 60 * 60 * 1000l;
        long time = System.currentTimeMillis() - interval;
        if (subUnderwriter.getCreatedAt().getTime() < time) {
            return;
        }

        // 更新分销人等级
        int fansCount = subUnderwriterFansCount(subUnderwriterId);
        int levelId = 0;
        if (fansCount >= 1000) {
            levelId = 3;
        } else if (fansCount >= 300) {
            levelId = 2;
        } else if (fansCount >= 50) {
            levelId = 1;
        }

        ClientInfo subUnderwriterInfo = accountManager.getInfo(subUnderwriterId);
        if (levelId > subUnderwriterInfo.getLevelId()) {
            accountManager.updateLevel(subUnderwriterId, levelId);
            // 加入升级模板消息推送
            ThClientPlatforms clientPlatform = accountManager
                .getClientPlatformByUserId(subUnderwriterId);
            if (clientPlatform != null) {
                ThUserLevels level = accountManager.userLevelGet(levelId);
                TemplateMessageUtil.sendLevelUpMessage(clientPlatform.getOpenId(),
                    subUnderwriterInfo.getName(), level.getTitle());
            }
        }

    }

    public BigDecimal getOrderProfitShare(final int orderID) {
        return suDAO.getOrderProfitShare(orderID);
    }

    public static void main(String[] args) {
        int a = 135;
        BigDecimal aa = new BigDecimal(Integer.parseInt("123")).divide(new BigDecimal(100));
        System.out.println(aa);
    }
}
